<script setup lang="ts">
import { ref } from 'vue'
import { updatePassword } from '@/api/user'
import type { PasswordUpdateForm } from '@/types/user'
import { ElMessage } from 'element-plus'

const passwordForm = ref<PasswordUpdateForm>({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const loading = ref(false)

// 更新密码
const updatePwd = async () => {
  try {
    if (passwordForm.value.newPassword !== passwordForm.value.confirmPassword) {
      ElMessage.error('两次输入的密码不一致')
      return
    }

    loading.value = true
    await updatePassword(passwordForm.value)
    ElMessage.success('密码修改成功')
    passwordForm.value = {
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    }
  } catch (error) {
    console.error('修改密码失败:', error)
    ElMessage.error('修改密码失败')
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <div class="password-container">
    <el-card>
      <template #header>
        <div class="header">
          <span>修改密码</span>
        </div>
      </template>

      <el-form
        :model="passwordForm"
        label-width="100px"
        label-position="left"
        @submit.prevent="updatePwd"
      >
        <el-form-item label="原密码" prop="oldPassword">
          <el-input
            v-model="passwordForm.oldPassword"
            type="password"
            show-password
          />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            show-password
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="loading" native-type="submit">
            保存
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<style scoped>
.password-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
